﻿angular.module('Caltech').controller('customerEquipmentController', function ($scope, Restangular, ngTableParams, $stateParams, $location) {
    'use strict';

    $scope.customer = { name: '' };

    $scope.search = function (index, total) {
        $scope.tableParams = new ngTableParams({
            page: index || 1,
            count: 10
        }, {
            counts: [10, 15, 20],
            getData: function ($defer, params) {
                Restangular.all('customerEquipment')
                    .getList({
                        page: params.page(),
                        count: total || params.count(),
                        customerId: $scope.customer.id
                    }).then(function (customerEquipment) {
                        params.total(customerEquipment.total);
                        $defer.resolve(customerEquipment);

                        if (params.page() > 1) {
                            $location.search('pageIndex', params.page());
                            $location.search('pageTotal', params.count());
                        }
                        $location.search('customerId', $scope.customer.id || undefined);
                    });
            }
        });
    };

    $scope.getCustomerList = function (nameFitler) {
        return Restangular.all('customer/list').getList({
            name: nameFitler
        });
    };

    $scope.updateState = function (item) {
        if (!item) {
            $scope.customer = {};
        } else if (typeof (item) === 'object') {
            $scope.customer = item;

            $location.search('customerId', item.id);
            $location.search('customerName', item.name);

            if ($scope.tableParams) {
                $scope.tableParams.reload();
            } else {
                $scope.search();
            }
        }
    };

    $scope.import = function (file) {
        alert('Being developed');
    };

    if ($stateParams.customerId || $stateParams.pageIndex) {
        $scope.customer = {
            name: $stateParams.customerName,
            id: $stateParams.customerId
        };

        $scope.search($stateParams.pageIndex, $stateParams.pageTotal);
    } else {
        $scope.search();
    }
});